package com.sample.wanandroidx.basic

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.CallSuper
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.LifecycleOwner
import androidx.viewbinding.ViewBinding
import com.classic.common.MultipleStatusView
import com.hjq.bar.OnTitleBarListener
import com.hjq.bar.TitleBar
import com.sample.library.IView
import com.sample.library.ext.FragmentViewBindingInflater
import com.sample.library.ext.ProxyClickListener
import com.sample.library.ext.removeEscapeCharacter
import com.sample.library.util.ViewUtil
import com.sample.library.util.ViewUtil.setOnProxyClickListener
import com.sample.wanandroidx.support.IUrls
import com.xiasuhuei321.loadingdialog.view.LoadingDialog

abstract class BaseFragment<VB : ViewBinding>(private val bindingInflater: FragmentViewBindingInflater<VB>) : Fragment(), IView,
                                                                                                              IUrls,
                                                                                                              View.OnClickListener,
                                                                                                              OnTitleBarListener,
                                                                                                              ProxyClickListener {

    private var mHandler: Handler? = null

    private fun getHandler(): Handler? = mHandler

    private var _binding: VB? = null

    protected val binding: VB get() = _binding!!

    abstract fun initialization()

    /*
     * 可见的时候才执行
     */
    open fun initLazyLoad() {}

    /**
     * 绑定视图监听事件
     */
    open fun bindingListener(vararg views: View) = views.forEach { it.setOnProxyClickListener(this) }

    /**
     * 标题栏
     */
    protected var titlebar: TitleBar? = null

    /**
     * 加载提示
     */
    private var loadingDialog: LoadingDialog? = null

    /**
     * 多种状态的 View 的切换
     */
    protected var multipleStatusView: MultipleStatusView? = null

    /**
     * 在主线程中执行
     */
    open fun post(runnable: () -> Unit) = getHandler()?.post(runnable)

    /**
     * 在主线程中延时执行
     */
    open fun postDelayed(delayMilli: Long, runnable: () -> Unit) = getHandler()?.postDelayed(runnable, delayMilli)

    /**
     * 是否使用 加载视图
     */
    open var useLoadingView: Boolean = true

    /**
     * 懒加载
     */
    private var isFirstLoad = true

    //网络已恢复 initLazyLoad()

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        _binding = bindingInflater.invoke(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mHandler = Handler(Looper.getMainLooper())

        val list: List<View> = ViewUtil.getAllChildViews(view)
        multipleStatusView = list.find { it is MultipleStatusView } as MultipleStatusView?
        if (multipleStatusView == null) {
            if (view is MultipleStatusView) {
                multipleStatusView = view
            }
        }
        multipleStatusView?.setOnRetryClickListener {
            showLoading()
            initialization()
            initLazyLoad()
        }
        titlebar = list.find { it is TitleBar } as TitleBar?
        titlebar?.setOnTitleBarListener(this)
        titlebar?.leftView?.visibility = View.GONE
        showLoading()
        initialization()
    }

    open fun setTitle(title: String) {
        titlebar?.setTitle(title.removeEscapeCharacter())
    }

    override fun showLoadingDialog(resId: Int) {
        showLoadingDialog(getString(resId))
    }

    override fun <T : View> findViewWithId(id: Int): T {
        return binding.root.findViewById(id)
    }

    override fun updateLoadingDialog(progress: String) {
        post {
            loadingDialog?.setLoadingText(progress)
        }
    }

    override fun showLoadingDialog(desc: String) {
        dismissLoadingDialog()
        loadingDialog = LoadingDialog(context).setLoadingText(desc)
        loadingDialog?.show()
    }

    override fun dismissLoadingDialog() {
        loadingDialog?.close()
    }

    override fun withContext(): FragmentActivity? {
        return activity
    }

    @CallSuper
    override fun onDestroyView() {
        super.onDestroyView()
        dismissLoadingDialog()
        _binding = null
        mHandler?.removeCallbacksAndMessages(null)
        mHandler = null
    }

    override fun showContent() {
        if (useLoadingView) multipleStatusView?.showContent()
    }

    override fun showLoading() {
        if (useLoadingView) multipleStatusView?.showLoading()
    }

    override fun closePage() {
        activity?.finish()
    }

    override fun showEmpty() {
        multipleStatusView?.showEmpty()
    }

    override fun showError() {
        if (useLoadingView) multipleStatusView?.showError()
        dismissLoadingDialog()
    }

    override fun showNoNetwork() {
        if (useLoadingView) multipleStatusView?.showNoNetwork()
        dismissLoadingDialog()
    }

    override fun getLifecycleOwner(): LifecycleOwner {
        return this
    }

    override fun onResume() {
        super.onResume()
        if (isFirstLoad) {
            initLazyLoad()
        }
        isFirstLoad = false
    }

    /**
     * @param eventId 事件ID
     */
    override fun onEvent(eventId: Int) {

    }

    override fun onClick(v: View) {

    }

    override fun onLeftClick(v: View?) {

    }

    override fun onTitleClick(v: View?) {
    }

    override fun onRightClick(v: View?) {
    }

    override fun invoke(v: View) {
    }
}
